<?php

namespace app\common\library\xmwechat\offiaccount;

use app\common\library\xmwechat\SingletonTrait;
use app\common\library\xmwechat\WechatService;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\OfficialAccount\Application;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use think\exception\HttpResponseException;
use think\Response;

/**
 * 菜单管理
 */
class MenuService extends WechatService
{
    protected ?Application $app;
    protected string $accessToken;

    use SingletonTrait;

    /**
     * @throws InvalidArgumentException
     */
    public function __construct()
    {
        parent::__construct();
        if (empty($this->offiAccountConfig['app_id']) || empty($this->offiAccountConfig['secret'])) {
            $this->result('请配置公众号appid或secret');
        }
        $offiAccountConfig = [
            'app_id' => $this->offiAccountConfig['app_id'],
            'secret' => $this->offiAccountConfig['secret'],
        ];
        $this->app         = new Application($offiAccountConfig);
        $accessToken       = $this->app->getAccessToken();
        $this->accessToken = $accessToken->getToken();
    }

    /**
     * 获取已发布的菜单
     * @return mixed|void
     * @throws TransportExceptionInterface
     * @throws ClientExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ServerExceptionInterface
     * @throws \Exception
     * @author jsjxsz <QQ:1365962177>
     */
    public function getMenu()
    {
        try {
            $response = $this->app->getClient()->get('cgi-bin/menu/get?access_token=' . $this->accessToken);
            if ($response->isFailed()) {
                // 出错了，处理异常
                $this->result($response->getContent());
            }
            $data = json_decode($response->getContent(), true);
            return $data['menu']['button'];
        } catch (\Exception $e) {
            $this->result($e->getMessage());
        }
    }

    /**
     * 保存并发布菜单 params menu matchRule
     * @param $params
     * @return bool
     * @throws \Exception
     * @author jsjxsz <QQ:1365962177>
     */
    public function saveAndPublish($params): bool
    {
        try {
            if (isset($params['matchRule']) && !empty($params['matchRule'])) {
                $response = $this->app->getClient()->postJson('cgi-bin/menu/addconditional', [
                    'button'    => $params['button'],
                    'matchrule' => $params['matchrule'],
                ]);
            } else {
                $response = $this->app->getClient()->postJson('cgi-bin/menu/create', ['button' => $params['button']]);
            }
            if ($response->isFailed()) {
                // 出错了，处理异常
                $this->result($response->getContent());
            }
            $result = json_decode($response->getContent(), true);
            if ($result['errcode'] == 0) {
                return true;
            }
        } catch (TransportExceptionInterface $e) {
            $this->result($e->getMessage());
        }
        return false;
    }

}